package com.imooc.api.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @version 1.0
 * @Author Mr.Yang
 * @Date 2024-08-20 18:47
 * @question: RabbitMQ 的配置类
 */

@Configuration
public class RabbitMQSMSConfig {

    //定义交换机的名称
    public static final String SMS_EXCHANGE = "sms_exchange";

    //定义队列的名称
    public static final String SMS_QUEUE = "sms_queue";

    //统一定义路由key
    public static final String ROUTING_KEY_SMS_SEND_LOGIN = "imooc.sms.send.login";

    //创建交换机
    @Bean(SMS_EXCHANGE)
    public Exchange exchange() {
        return ExchangeBuilder
                .topicExchange(SMS_EXCHANGE)
                .durable(true)
                .build();
    }

    //创建队列
    @Bean(SMS_QUEUE)
    public Queue queue() {
        //return new Queue(SMS_QUEUE);
        return QueueBuilder
                .durable(SMS_QUEUE)
                .withArgument("x-message-ttl", 30 * 1000) //毫秒 现在等于是30秒
                .withArgument("x-dead-letter-exchange", RabbitMQSMSConfig_Dead.SMS_EXCHANGE_DEAD) //死信交换机
                .withArgument("x-dead-letter-routing-key", RabbitMQSMSConfig_Dead.ROUTING_KEY_SMS_DEAD) //私信交换机的路由routingKey
                .withArgument("x-max-length", 6) //队列的长度 比如发了10条 死信交换机就得吞掉 10-6=4(条)
                .build();
//        return QueueBuilder
//                .durable(SMS_QUEUE)
//                .build();
    }

    //创建绑定关系
    @Bean
    public Binding smsBinding(@Qualifier(SMS_EXCHANGE) Exchange exchange, @Qualifier(SMS_QUEUE) Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("imooc.sms.#")
                .noargs(); //noargs --> 无需携带参数
    }

}

